package com.yaoxun.bored.shiro.realm;

import java.util.Set;

import javax.inject.Inject;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.yaoxun.bored.model.sys.user.SessionUser;
import com.yaoxun.bored.model.sys.user.User;
import com.yaoxun.bored.service.sys.role.RoleService;
import com.yaoxun.bored.service.sys.user.UserService;

public class BaseRealm extends AuthorizingRealm {

	@Inject
	private UserService userService;
	
	@Inject
	private RoleService  roleService;
	
	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String account = (String) token.getPrincipal(); //获取账号
		User user = userService.selectOneUser(account);
		if(user != null) {
			String pwd = user.getPwd();
			String salt = user.getSalt();
			SessionUser sessionUser = new SessionUser(user.getUserId(), user.getAccount());
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sessionUser, pwd, ByteSource.Util.bytes(salt), getName());
			return info;
		}else {
			throw new UnknownAccountException();
		}		
	}

	//授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SessionUser user = (SessionUser) principals.getPrimaryPrincipal();
		Set<String> stringPermissions = roleService.selectAuthCode(user.getSessionRoles()); 
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.setStringPermissions(stringPermissions);
		return simpleAuthorizationInfo;
	}
}
